//
//  NGForumViewController.swift
//  NingguoForum
//
//  Created by zhengsw on 2025/7/17.
//  Copyright © 2025 zhengsw. All rights reserved.
//

import UIKit
import SnapKit
import ObjectMapper
import RxSwift

class NGForumViewController: NGBaseViewController {
    
    // MARK: - Properties
    private let model: ResponseCircleClassItemModel?
    private var titles: [ResponseForumDetailListModel] = []
    private var selectedIndex = 0
    private let parameters = NSMutableDictionary()
    
    // MARK: - UI Components
    private lazy var titleBarView: NGTitleBarView = {
        let titleBarView = NGTitleBarView()
        titleBarView.delegate = self
        return titleBarView
    }()
    
    private lazy var forumTableView: NGForumTableView = {
        let tableView = NGForumTableView(titles: titles)
        tableView.delegate = self
        return tableView
    }()
    
    // MARK: - Initialization
    init(model: ResponseCircleClassItemModel?) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidDisappear(_ animated: Bool) {
        print("viewDidDisappear")
    }
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadInitialData()
        parseURLAndLoadData()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        view.backgroundColor = .white
        
        view.addSubview(titleBarView)
        view.addSubview(forumTableView)
        
        titleBarView.snp.makeConstraints { make in
            make.top.equalTo(KDevice_NaviBar_Height)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        forumTableView.snp.makeConstraints { make in
            make.top.equalTo(titleBarView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    // MARK: - Data Loading
    private func loadInitialData() {
        // 加载初始数据
        for i in 0..<titles.count {
            loadData(for: i, isRefresh: true)
        }
    }
    
    private func parseURLAndLoadData() {
        guard let url = URL(string: model?.link ?? ""),
              let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else {
            return
        }
        
        print(queryItems) // 输出: fid=305&circleId=129
        
        for item in queryItems {
            parameters.setValue(item.value ?? "", forKey: item.name)
        }
        
        // 1. 先验证参数
        guard let parameters = parameters as? [String: String] else {
            print("Invalid parameters format")
            return
        }
        
        HttpManager.sharedInstance.getDetailCircleClass(patameter: parameters ) { [weak self] (successd: Dictionary<String, AnyObject>) in
            guard let self = self else { return }
            
            // 2. 安全地解析数据
            guard let list = successd["list"] as? [[String: Any]] else {
                print("Invalid list format")
                return
            }
            
            // 3. 安全地映射数据
            let mappedTitles = Mapper<ResponseForumDetailListModel>().mapArray(JSONArray: list)
               self.titles = mappedTitles
            
            // 4. 在主线程更新UI
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                
                // 5. 检查对象是否还存在
                guard !self.titles.isEmpty else {
                    print("No titles to configure")
                    return
                }
                
                self.titleBarView.configure(titles: self.titles)
                
                self.parameters.setValue("1", forKey: "p")
                self.parameters.setValue("10", forKey: "step")
                self.forumTableView.configTitles(titles: self.titles, paramters: self.parameters)
            }
            
        } fail: { [weak self] (fail) in
            print("加载数据失败: \(fail)")
        }
    }
    
    private func loadData(for tabIndex: Int, isRefresh: Bool) {
        // 模拟网络请求
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            let data: [Any] = []
            
            if isRefresh {
                self?.forumTableView.reloadData(for: tabIndex)
            } else {
                // 加载更多数据
                // self?.forumTableView.appendDataSource(data, for: tabIndex)
            }
            
            self?.forumTableView.endRefreshing(for: tabIndex)
            self?.forumTableView.endLoadMore(for: tabIndex)
        }
    }
    deinit {
        print("NGForumViewController deinit")
        }
}

// MARK: - NGTitleBarViewDelegate
extension NGForumViewController: NGTitleBarViewDelegate {
    func titleBarView(_ titleBarView: NGTitleBarView, didSelectItemAt index: Int) {
        selectedIndex = index
        forumTableView.selectTab(at: index)
    }
}

// MARK: - NGForumTableViewDelegate
extension NGForumViewController: NGForumTableViewDelegate {
    func forumTableView(_ tableView: NGForumTableView, didSelectItemAt indexPath: IndexPath, in tabIndex: Int) {
        print("点击了 \(titles[tabIndex]) 的第 \(indexPath.row) 行")
        
        let vc = NGHomeDetailViewController()
        
        var link = "/mag/circle/v1/forum/threadViewPage?tid=4169104&circle_id=218&mag_hide_progress=1"
        if link.components(separatedBy: "https").count == 1 {
            link = Config.requestAddress + link
        }
        vc.configUrl(link: link)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func forumTableView(_ tableView: NGForumTableView, didScrollToTab index: Int) {
        selectedIndex = index
        titleBarView.updateSelectedIndex(index)
        titleBarView.scrollToSelectedItem()
    }
    
    func forumTableView(_ tableView: NGForumTableView, didTriggerRefreshIn tabIndex: Int) {
        print("刷新 \(titles[tabIndex]) 的数据")
        loadData(for: tabIndex, isRefresh: true)
    }
    
    func forumTableView(_ tableView: NGForumTableView, didTriggerLoadMoreIn tabIndex: Int) {
        print("加载更多 \(titles[tabIndex]) 的数据")
        loadData(for: tabIndex, isRefresh: false)
    }
}
